package cn.virens.cmpt.server.runnable;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import cn.virens.cmpt.server.channel.ChannelSimple;
import cn.virens.cmpt.server.handler.AsynchronousSocketAcceptHandler;
import cn.virens.cmpt.server.listener.DataEncoder;

public class ChannelReadRunnable extends AbstractRunnable<ByteBuffer> {
	private final AsynchronousSocketChannel socketChannel;
	private final DataEncoder dataEncoder;

	public ChannelReadRunnable(ChannelSimple channel) {
		super(channel);

		this.dataEncoder = channel.getDataEncoder();
		this.socketChannel = channel.getChannel();
	}

	@Override
	public void run() {
		if (channel.isOpen() && !channel.isRemove()) {
			// 将数据包进行编码，如果字节帧为空就放弃该数据包
			ByteBuffer buffer = dataEncoder.encode(channel, packet);
			if (buffer == null || buffer.remaining() == 0) return false;

			// 通过连接对字节帧进行发送
			socketChannel.write(buffer, buffer, writeCompletionHandler);
		} else {
			return false;
		}

		return true;
	}

}
